export async function downloadFile(urlPath: string, fileName: string) {
  const response = await fetch(urlPath);
  const contentLength = response.headers.get("Content-Length");
  if (!contentLength) {
    console.error("Content-Length header is missing.");
    return;
  }
  const total = parseInt(contentLength, 10);
  let loaded = 0;
  if (response) {
    const reader = response.body?.getReader();
    const stream = new ReadableStream({
      start(controller) {
        function push() {
          reader?.read().then(({ done, value }) => {
            if (done) {
              controller.close();
              return;
            }
            loaded += value.length;
            const progress = (loaded / total) * 100;
            console.log(progress);
            controller.enqueue(value);
            push();
          });
        }
        push();
      },
    });

    const newResponse = new Response(stream);
    const blob = await newResponse.blob();
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.style.display = "none";
    a.href = url;
    a.download = fileName;
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
  }
}
